// pages/productDetail/productDetail.js
const util = require('../../utils/util.js')
const API = require('../../utils/api.js')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    product: {},
    showProduceInfo: true,//是否展开生产信息，默认展开
    showTransportInfo: true,
    showSellInfo: true,
    producer: {},
    transportRecordList: [],
    seller: {},
    initFail: true,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      product: JSON.parse(options.data)
    })
    console.log(JSON.parse(options.data))
    this.initData(this.data.product)
  },

  /**
   * 请求产品的生产，物流和销售数据
   */
  initData: function(product) {
    let that = this
    wx.showLoading({
      title: '加载中',
    })
    util.getData(API.Producer.find, {"id": product.producer_id}).then(producerRes => {
      that.setData({
        producer: producerRes
      })
      util.getData(API.Product.find, {"product_id": product.id}).then(recordRes => {
        that.setData({
          transportRecordList: recordRes
        })
        util.getData(API.Seller.find, {"id": product.seller_id}).then(sellerRes => {
          that.setData({
            seller: sellerRes,
            initFail: false
          })
          wx.hideLoading()
        },err => {
          wx.hideLoading()
          that.setData({
            initFail: true
          })
        })
      },err => {
        wx.hideLoading()
        that.setData({
          initFail: true
        })
      })
    },err => {
      wx.hideLoading()
      that.setData({
        initFail: true
      })
    })
  },

  /**
   * 点击分类标题，设置展开或收起
   */
  tapTitle: function(e) {
    let type = e.currentTarget.dataset.type
    if (type == "produce") {
      this.setData({
        showProduceInfo: !this.data.showProduceInfo
      })
    } else if (type == "transport") {
      this.setData({
        showTransportInfo: !this.data.showTransportInfo
      })
    } else if (type == "sell") {
      this.setData({
        showSellInfo: !this.data.showSellInfo
      })
    }
  },

  /**
   * 点击产品图片，跳转查看大图
   */
  tapProductImage: function() {
    wx.navigateTo({
      url: '/pages/webview/webview?url=' + this.data.product.imageUrl,
    })
  },

  /**
   * 点击加载失败，重试请求
   */
  tapInitFail: function() {
    this.initData(this.data.product)
  },

})